<style lang="scss" scoped>
    @import './ui-main.scss';
</style>
<template>
    <div ref="main" class="ui-main ui flex column item one">
        <div v-if="hasBackBtn || title || $slots.topTitle" class="ui mini top attached menu m-0 ui-menu">
            <!-- 返回按钮 -->
            <span v-if="hasBackBtn" class="header item goback" @click="goBack()"><span><i class="icon chevron left"></i></span></span>
            <span class="header item border-0" style="top:-2px"><span>{{title}}</span></span>
            <slot name="topTitle"></slot>
        </div>
        <slot name="topTools"></slot>
        <div class="ui item" style="background: #fff;">
            <transition name="fade">
                <div class="topAccordion" v-show="show" ref="topAccordion">
                    <slot name="topAccordion"></slot>
                </div>
            </transition>
            <slot name="toolbarTop"></slot>
            <div class="topAccordion-bar ui flex" v-if="showToggle || showToolbar">
                <div ref="toolbar" class="item one topAccordion-bar-toolbar">
                    <span style="float:right;" v-if="total + 1 > 1">
                       <el-pagination small
                           background
                           :layout="total > pageSize ? 'total, prev, pager, next, sizes':'total, sizes'"
                           :total="total"
                           :page-size="pageSize"
                           :page-sizes="[20, 50, 100]"
                           :current-page="pageNum"
                           @size-change="sizeChange"
                           @current-change="pageChange">
                       </el-pagination>
                    </span>
                    <slot name="toolbar"></slot>
                </div>
                <a class="toggle item" @click="topAcoSwitch" v-if="showToggle">
                    <i class="chevron circle icon" :class="{up:show,down:!show}"></i>
                    {{toggleName}}
                </a>
            </div>
        </div>
        <div class="ui flex item column one block" :class="{'p-5':noPadding !== ''}">
            <div class="ui item one">
                <div
                    style="background: #fff;"
                    class="ui content flex column"
                    :class="{'p-5':noPadding !== '' , 'scrollbar scroll-no-track scroll-teal': noScrollbar !== ''}">
                    <slot></slot>
                </div>
            </div>
            <slot name="footerBar"></slot>
        </div>
        <ui-nest-router v-if="!isSplit"/>
    </div>
</template>
<script>
    export default {
        name: 'ui-main',
        // ui-split会给子组件传播事件, 这里用inject接收此事件
        inject: {
            isSplit: {
                from: 'isSplit',
                default: false
            }
        },
        props: {
            back: {
                default: false,
                type: Boolean
            },
            title: String,
            noPadding: String,
            noScrollbar: String
        },
        data() {
            return {
                showToggle: true,
                showToolbar: true,
                show: true,
                toggleName: '',
                main: false,
                holdPagination: false,
                formCacheTimer:null,
            }
        },
        computed: {
            // 传入分页数据
            pageSize() {
                const m = this._getMain(this)
                if (m.searchData && m.searchData.pageSize!==undefined) {
                    return m.searchData.pageSize
                }
                return 20 //未定义时,默认20
            },
            // pageNumber改变时分页也改变
            pageNum() {
                const m = this._getMain(this)
                if (m.searchData && m.searchData.pageNumber!==undefined) {
                    return m.searchData.pageNumber
                }
                return 1 //未定义时,默认1
            },
            total() {
                if (this._getMain(this).tabObj) {
                    return this._getMain(this).tabObj.total
                }
                return false
            },
            hasBackBtn() {
                return this.$listeners.back || this.back
            },
            topTitle() {
                return this.$slots.topTitle
            }
        },
        mounted() {
            // this.log(this.app)
            this.$nextTick(() => {
                const slots = this.$slots;

                //根据折叠栏插槽是否存在, 判断是否显示
                if (slots.topAccordion) {
                    this.showToggle = true
                    this.toggleName = slots.topAccordion[0].data.attrs.name  //获取折叠栏标题
                }else{
                    this.showToggle = false
                }

                //根据工具栏插槽是否存在, 判断是否显
                slots.toolbar ? this.showToolbar = true : this.showToolbar = false

                this.addFormCache()
                this.$bui.mainComp = this
            })
        },
        beforeDestroy(){
            // 表单缓存功能清理
            if (this.formCacheTimer) {
                clearTimeout(this.formCacheTimer)
                this.saveFormCache(window.addFormCacheArg)
                window.addFormCacheArg = null
            }
            sessionStorage.removeItem('addFormCache')
        },
        methods: {
            _getMain(par) {
                try{
                    if (this.main) return this.main
                    if (par.$vnode.componentOptions.tag === 'ui-nest') {
                        if (par.$parent.$$uiTableLoad) {
                            return par.$parent
                        }
                        return false

                    }
                    if (par.tabObj && par.$$uiTableLoad) {
                        this.main = par
                        return par
                    }
                    return this._getMain(par['$parent'])
                }catch(err){
                    return false;
                }
            },
            sizeChange(val) {
                this.holdPagination = true;
                this._getMain(this.$parent).$$pageChange(1)
                if (this._getMain(this.$parent).$$pageSizeChange) {
                    this._getMain(this.$parent).$$pageSizeChange(val)
                }
            },
            pageChange(num) {
                if (this._getMain(this.$parent).$$pageChange) {
                    setTimeout(() => {
                      this._getMain(this.$parent).$$pageChange(num)
                    }, 100)
                }
            },
            goBack() {//返回按钮
                if (this.$listeners.back) { //参数 @back="callback" 回调形式,调用自定义回调
                    this.$emit('back')
                }else{ // 参数 back 形式, 调用默认的返回功能
                    this.$eventHub.$emit('closeThis', 'close'); //提交关闭指令给关闭窗口的组件
                    this.$root.$emit('closeThis', 'close'); //提交关闭指令给关闭窗口的组件
                }
            },
            topAcoSwitch() {
                this.show = !this.show;
                //提交折叠栏状态到vuex
                this.$store.commit('tableEdit/settopAccordion', this.show)
            },
            addFormCache(){// 表单临时保存
                setTimeout(() => {//若在部分组件渲染前执行会报错
                    const arg = sessionStorage.getItem('addFormCache') //获取v-has按钮分号参数
                    if (arg==null || arg==='') {
                        return
                    }
                    window.addFormCacheArg = arg
                    sessionStorage.removeItem('addFormCache')
                    const uiMain = this.$parent.$vnode.componentOptions.tag === 'ui-nest' ? this.$parent.$parent : this.$parent
                    if (typeof uiMain.form==='object') {
                        this.$http({
                            url: 'admin/form/tpdata',// 读取
                            method: 'post',
                            data: {
                                identity:arg
                            }
                        }).then((res) => {
                            // 还原当前表单数据
                            if (res.data) {
                                uiMain.form = {...res.data}
                                this.$message('已恢复上次编辑内容')
                            }

                            // 页面form变化时提交临时表单数据
                            uiMain.$watch('form',() => {
                                clearTimeout(this.formCacheTimer)
                                this.formCacheTimer = setTimeout(() => {
                                    this.saveFormCache(arg)
                                }, 3000);
                            }, { deep: true })
                        })
                    }

                });
            },
            saveFormCache(arg){
                this.$http({
                    url: 'admin/form/saveOrUpdate',// 保存
                    method: 'post',
                    data: {
                        identity: arg,
                        json_data: JSON.stringify(this.$parent.form)
                    }
                })
            }
        }
    }
</script>
